package com.boruan.shengtangfeng.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boruan.shengtangfeng.api.jwt.UserSubject;
import com.boruan.shengtangfeng.api.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.dao.IMusicCollectionDao;
import com.boruan.shengtangfeng.core.dao.IUserDao;
import com.boruan.shengtangfeng.core.dao.IVideoDao;
import com.boruan.shengtangfeng.core.dto.*;
import com.boruan.shengtangfeng.core.dto.mapper.SmallVideoDtoMapper;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.service.*;
import com.boruan.shengtangfeng.core.service.impl.UserService;
import com.boruan.shengtangfeng.core.utils.*;
import com.boruan.shengtangfeng.core.vo.*;
import com.boruan.shengtangfeng.core.vo.mapper.MusicVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.VideoCategoryVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.VideoCommentVoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("api/smallVideo")
@Api(value = "", tags = {"V4G 小视频相关接口"})
public class SmallVideoApi {

    @Autowired
    private IMusicService musicService;
    @Autowired
    private IMusicCollectionDao musicCollectionDao;
    @Autowired
    private IVideoService videoService;
    @Autowired
    private IVideoCommentService videoCommentService;
    @Autowired
    private IAttentionService attentionService;
    @Autowired
    private IFavoritesService favoritesService;
    @Autowired
    private IAccoladeService accoladeService;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private UserService userService;
    @Autowired
    private IVideoDao videoDao;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 定义日志对象
     */
    private static Logger log = LoggerFactory.getLogger(HttpsUtil.class);


    @PostMapping("/getMusic")
    @ApiOperation(value = "V4G-1 获取音乐列表", notes = "")
    public GlobalReponse<PageQuery<Music>> getMusic(@RequestBody MusicPageSearchDto musicPageSearch) {
        if (musicPageSearch.getKeyword() != null && musicPageSearch.getKeyword().equals("")) {
            musicPageSearch.setKeyword(null);
        }
        Music search = new Music();
        PageQuery<Music> pageQuery = new PageQuery<Music>();
        List<Music> list = new ArrayList<>();

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        search.set("keyword", musicPageSearch.getKeyword());

        pageQuery.setPageNumber(musicPageSearch.getPageNo());
        //查看我已经关注的
        if (musicPageSearch.getType() != null && 0 == musicPageSearch.getType()) {
            //用户没登录显示全部
            if (userSubject == null) {
                musicService.pageQuery(pageQuery, search);
                list = pageQuery.getList();
            } else {
                musicService.pageCollectionMusic(pageQuery, userSubject.getId());
                list = pageQuery.getList();
            }
        } else {
            if (musicPageSearch.getType() != null && 1 == musicPageSearch.getType()) {
                search.setIsHot(musicPageSearch.getIsHot());
            }
            musicService.pageQuery(pageQuery, search);
            list = pageQuery.getList();
        }
        List<MusicVo> vos = MusicVoMapper.MAPPER.toVo(list);
        vos.forEach(vo -> {
            MusicCollection collection = null;
            if (userSubject != null) {
                collection = musicCollectionDao.createLambdaQuery().andEq(MusicCollection::getMusicId, vo.getId()).andEq(MusicCollection::getUid, userSubject.getId()).andEq(MusicCollection::getIsDeleted, false).single();
            }
            vo.setIsCollection(collection == null ? 0 : 1);
        });

        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping(value = "/collectMusic/{musicId}")
    @ApiOperation(value = "V4G-2 取消/收藏音乐", notes = "")
    public GlobalReponse<Boolean> collectMusic(@PathVariable Long musicId) {
        if (musicId == null) {
            return GlobalReponse.fail("请传入正确的参数");
        }
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        return musicService.collectMusic(musicId, userId);
    }

    @PostMapping("/saveVideo")
    @ApiOperation(value = "V4G-3 发布视频", notes = "新增、修改保存")
    public GlobalReponse saveVideo(@RequestBody SmallVideoDto videoDto) throws IOException {

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        if (videoDto.getScope() == 2 && videoDto.getClasses() == null) {
            return GlobalReponse.fail("请选择可见班级");
        }
        if (videoDto.getId() != null) {
            Video video = videoService.findId(videoDto.getId());
            video.setScope(videoDto.getScope());
            video.setAddress(videoDto.getAddress());
            video.setLongitude(videoDto.getLongitude());
            video.setLatitude(videoDto.getLatitude());
            video.setCityCode(videoDto.getCityCode());
            video.setStatus(0);
            video.setCategoryId(videoDto.getCategoryId());
            video.setContent(videoDto.getContent());
            video.setTitle(videoDto.getTitle());
            video.setUploadType(1);
            if (StringUtils.isNotBlank(videoDto.getImage())) {
                video.setImage(videoDto.getImage());
            } else {
                video.setImage(video.getContent() + "?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast");
            }

            videoService.saveSmall(video, videoDto.getClasses(), videoDto.getFriendIds(), userSubject.getId(), null, videoDto.getMusicId());
        } else {
            Video video = SmallVideoDtoMapper.MAPPER.toEntity(videoDto);
            video.setPublishId(userSubject.getId());
            video.setPublisher(userSubject.getName());
            video.setPublisherIcon(userSubject.getIcon());
            video.setLongitude(videoDto.getLongitude());
            video.setLatitude(videoDto.getLatitude());
            video.setCreateBy(userSubject.getName());
            video.setCreateTime(new Date());
            video.setPublishDate(new Date());
            video.setStatus(0);
            video.setUploadType(1);
            video.setReadNum(0);
            video.setCommentNum(0);
            video.setThumpUpNum(0);
            video.setRecommend(false);
            video.setIsDeleted(false);
            video.setShareNum(0);
            video.setType(2);
            if (StringUtils.isNotBlank(videoDto.getImage())) {
                video.setImage(videoDto.getImage());
            } else {
                video.setImage(video.getContent() + "?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast");
            }
            //video.setImage(video.getContent() + "?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast");
            videoService.saveSmall(video, videoDto.getClasses(), videoDto.getFriendIds(), userSubject.getId(), null, videoDto.getMusicId());
        }
        return GlobalReponse.success();
    }

    @GetMapping("/locationToAddress")
    @ApiOperation(value = "V4G-4 坐标解析地址", notes = "location是坐标，经度在前，纬度在后")
    public GlobalReponse locationToAddress(@ApiParam("坐标") @RequestParam(value = "location") String location) {
        String mapKey = "1c7aedcb37df86affbd18d17fe9b9ab5";
        String url = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=" + location + "&key=" + mapKey + "&radius=1000&extensions=all";
        String res = HttpsUtil.httpMethodGet(url, "UTF-8");
        JSONObject jsonObject = JSON.parseObject(res);
        System.out.println(jsonObject.getString("status"));
        if (jsonObject.getString("status").equals("1")) {
            JSONObject regecode = jsonObject.getJSONObject("regeocode");
            JSONArray pois = regecode.getJSONArray("pois");
            String province = regecode.getJSONObject("addressComponent").getString("province");
            String city = regecode.getJSONObject("addressComponent").getString("city");
            String district = regecode.getJSONObject("addressComponent").getString("district");
            String city_code = regecode.getJSONObject("addressComponent").getString("adcode");
            List<String> address = new ArrayList<String>();
            address.add(province);
            if (city != "[]") {
                address.add(city);
            }
            address.add(district);
            for (Object o : pois) {
                Map item = (Map) o;
                if (address.size() < 10) {
                    address.add((String) item.get("name"));
                }
            }
            return GlobalReponse.success("查询成功").setData(address).setData1(city_code);
        } else {
            return GlobalReponse.success("查询失败");
        }
    }

    @GetMapping("getVideoCategory")
    @ApiOperation(value = "NO:6-4 获取小视频类别", notes = "")
    public GlobalReponse<List<VideoCategoryVo>> getVideoCategory() {
        VideoCategory videoCategory = new VideoCategory();
        videoCategory.setType(2);
        List<VideoCategory> list = videoService.getCategoryList(videoCategory);

        ArrayList<VideoCategory> videoCategories = new ArrayList<>();
        for (VideoCategory category : list) {
            if (!category.getName().equals("全部")) {
                videoCategories.add(category);
            }
        }
        return GlobalReponse.success(VideoCategoryVoMapper.MAPPER.toVo(videoCategories));
    }

    /**
     * @return
     * @description: 小视频二级评论
     * guojiang
     */
    @PostMapping(value = "/videoSecondComment")
    @ApiOperation(value = "NO:6-5 小视频二级评论", notes = "")
    public GlobalReponse<VideoCommentVo> videoSecondComment(@RequestBody VideoCommentDto videoCommentDto) {
        GlobalReponse globalReponse = null;
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        VideoComment comment = new VideoComment();
        Integer check = CommentUtil.checkComment(videoCommentDto.getContent());
        if (check == 2) {
            comment.setStatus(1);
            globalReponse = GlobalReponse.success(VideoCommentVoMapper.MAPPER.toVo(comment));
        } else if (check == 1) {
            comment.setStatus(0);
            globalReponse = GlobalReponse.fail("您的评论包含敏感词，需要等待客服审核");
        } else if (check == 0) {
            return GlobalReponse.fail("您的评论包含敏感词禁止评论");
        }
        comment.setContent(videoCommentDto.getContent());
        comment.setCreateBy(userSubject.getMobile());
        comment.setCreateTime(new Date());
        comment.setIsDeleted(false);
        comment.setVideoId(videoCommentDto.getVideoId());
        comment.setUserId(userSubject.getId());
        comment.setUserName(userSubject.getName());
        comment.setUserIcon(userSubject.getIcon());
        comment.setParentId(videoCommentDto.getCommentId());
        if(videoCommentDto.getCommentId() == null){
            comment.setParentId(0L);
        }
        comment.setThumpUpNum(0);
        videoCommentService.save(comment);
        Video video = videoDao.unique(videoCommentDto.getVideoId());
        video.setCommentNum(video.getCommentNum() + 1);
        videoDao.updateTemplateById(video);
        return globalReponse.setData(VideoCommentVoMapper.MAPPER.toVo(comment));
    }

    /**
     * @return
     * @description: 评论保存取消点赞
     * guojiang
     */
    @GetMapping("saveCancelAccolade")
    @ApiOperation(value = "NO:6-9 点赞/取消点赞评论，data是true是点赞成功，false是取消点赞成功", notes = "")
    public GlobalReponse<Boolean> saveAccolade(Long commentId) {
        UserSubject user = JwtUtil.getCurrentJwtUser();
        Accolade accolade = new Accolade();
        accolade.setArticleId(commentId);
        accolade.setType(3);
        accolade.setUserId(user.getId());
        accolade.setIsDeleted(false);
        accolade.setCreateBy(user.getName());
        accolade.setCreateTime(new Date());
        return videoCommentService.saveAccolade(accolade);
    }

    /**
     * @return
     * @description: 分享记录次数
     * guojiang
     */
    @GetMapping("saveShareNum")
    @ApiOperation(value = "NO:6-10 增加分享次数", notes = "")
    public GlobalReponse saveShareNum(Long videoId) {
        UserSubject user = JwtUtil.getCurrentJwtUser();
        return videoService.saveShareNum(user.getId(), videoId);
    }

    /**
     * @return
     * @description: 小视频列表
     * @Param
     * @author KongXH
     * @date 2020/8/12 15:57
     */
    @PostMapping("/videoPage")
    @ApiOperation(value = "NO:6-11 小视频列表", notes = "")
    public GlobalReponse<PageQuery<VideoVo>> videoPage(@RequestBody SmallVideoPageSearch videoPageSearch, HttpServletRequest request) {
        Long userId = null;
        String useraccount = jwtUtil.getUserAccountFromToken(jwtUtil.getToken(request));
        if (useraccount != null ) {
            if(jwtUtil.validateToken(jwtUtil.getToken(request))){
                UserSubject userDetails = jwtUtil.getJwtUserFromToken(jwtUtil.getToken(request));
                if(userDetails != null){
                    userId = userDetails.getId();
                }
            }
        }
        videoPageSearch.setUserId(userId);
        PageQuery<Video> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(videoPageSearch.getPageNo());
        pageQuery.setPageSize(videoPageSearch.getPageSize());
        pageQuery.setParas(videoPageSearch);
        List<User> userList = new ArrayList<>();
        if (videoPageSearch.getVideoType().equals(0)) {
            //查询推荐视频
            videoService.selectRecommendVideo(pageQuery);
        } else if (videoPageSearch.getVideoType().equals(1)) {
            UserSubject userSubject = JwtUtil.getCurrentJwtUser();
            if (userSubject != null) {
                //先查询是否有关注的好友
                List<Attention> attentionList = attentionService.findMyAttention(userSubject.getId());
                if (attentionList.size() > 0) {
                    pageQuery.setPara("userId", userSubject.getId());
                    videoService.selectAttentionVideo(pageQuery);
                    //如果关注好友未发布小视频则返回推荐视频
                    if (pageQuery.getList().size() == 0) {
                        pageQuery = new PageQuery<>();
                        pageQuery.setPageNumber(videoPageSearch.getPageNo());
                        pageQuery.setPageSize(videoPageSearch.getPageSize());
                        videoService.selectRecommendVideo(pageQuery);
                    }
                } else {
                    //没有关注的好友则推荐好友
                    if (videoPageSearch.getMobileList() != null && videoPageSearch.getMobileList().size() > 0) {
                        for (String mobile : videoPageSearch.getMobileList()) {
                            User user = userDao.createLambdaQuery().andEq(User::getMobile, mobile).andEq(User::getIsDeleted, false).single();
                            if (user != null) {
                                if (userList.size() < 20) {
                                    userList.add(user);
                                }
                            }
                        }
                    }
                    if (userList.size() == 0) {
                        userList = userDao.createLambdaQuery().andEq(User::getIsDeleted, false).limit(1, 20).select();
                    }

                }
            }
        } else if (videoPageSearch.getVideoType().equals(2)) {
            //查询同城视频
            pageQuery.setPara("cityName", videoPageSearch.getAddress());
            videoService.selectLocalVideo(pageQuery);
            //没有同城视频则显示推荐的
            if (pageQuery.getList().size() == 0) {
                pageQuery = new PageQuery<>();
                pageQuery.setPageNumber(videoPageSearch.getPageNo());
                pageQuery.setPageSize(videoPageSearch.getPageSize());
                videoService.selectRecommendVideo(pageQuery);
            }
        }

        ArrayList<VideoVo> vos = new ArrayList<>();
        if (pageQuery.getList() != null) {
            for (Video video : pageQuery.getList()) {
                //获取一次详情加一次阅读量
                video.setReadNum((video.getReadNum() == null ? 0 : video.getReadNum()) + 1);
                videoService.save(video);

                VideoVo vo = new VideoVo();
                //是否关注
                Attention attention = null;
                //是否点赞
                Accolade accolade = null;
                BeanUtils.copyProperties(video, vo);
                UserSubject user = JwtUtil.getCurrentJwtUser();
                if (user != null) {
                    //是否关注
                    attention = attentionService.findByFocusId(user.getId(), vo.getPublishId());
                    //是否点赞
                    accolade = accoladeService.getAccolade(user.getId(), vo.getId(), 2);
                }
                vo.setIsAttention(null == attention ? false : true);
                vo.setIsLike(null == accolade ? false : true);
                User publisher = userService.findById(vo.getPublishId());
                vo.setInvitationCode(publisher.getInvitationCode());
                vos.add(vo);
            }
        }
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery).setData1(userList);
    }

    /**
     * @return
     * @description: 查看小视频评论
     * guojiang
     */
    @GetMapping("getSmallVideoComment")
    @ApiOperation(value = "NO:6-12 查看小视频评论", notes = "")
    public GlobalReponse<SmallVideoCommentParentVo> getSmallVideoComment(Long videoId) {
        UserSubject user = JwtUtil.getCurrentJwtUser();
        if (user == null) {
            return videoService.getSmallVideoComment(null, videoId);
        }
        return videoService.getSmallVideoComment(user.getId(), videoId);
    }

    /**
     * @return
     * @description: 根据小视频id查看视频信息
     * guojiang
     */
    @GetMapping("smallVideoDetailForId")
    @ApiOperation(value = "NO:6-13 根据小视频id查看视频信息", notes = "")
    public GlobalReponse<SmallVideoDetailsForIdVo> smallVideoDetailForId(Long videoId) {
        UserSubject user = JwtUtil.getCurrentJwtUser();
        if (user != null) {
            return videoService.smallVideoDetailForId(user.getId(), videoId);
        }
        return videoService.smallVideoDetailForId(null, videoId);

    }
}
